package com.jxc.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jxc.dao.BaseDaoI;
import com.jxc.model.po.BasicArgument;
import com.jxc.model.po.Goods;
import com.jxc.model.po.Member;
import com.jxc.model.po.PointUsedRecord;
import com.jxc.model.po.Repertory;
import com.jxc.model.po.SaleReturnlist;
import com.jxc.model.po.SaleReturnlistItem;
import com.jxc.model.po.Salelist;
import com.jxc.model.po.SalelistItem;
import com.jxc.model.po.User;
import com.jxc.model.vo.DataGrid;
import com.jxc.model.vo.VSaleReturnlist;
import com.jxc.service.SaleReturnlistServiceI;
import com.jxc.util.Constants;

@Service("saleReturnlistService")
public class SaleReturnlistServiceImpl implements SaleReturnlistServiceI {

	@Autowired
	private BaseDaoI<Salelist> salelistDao;
	@Autowired
	private BaseDaoI<SalelistItem> salelistItemDao;
	@Autowired
	private BaseDaoI<SaleReturnlist> saleReturnlistDao;
	@Autowired
	private BaseDaoI<SaleReturnlistItem> saleReturnlistItemDao;
	@Autowired
	private BaseDaoI<BasicArgument> basicArumentDao;
	@Autowired
	private BaseDaoI<PointUsedRecord> pointUsedRecorDao;
	@Autowired
	private BaseDaoI<Goods> goodsDao;
	@Autowired
	private BaseDaoI<Member> memberBaseDao;

	@Override
	public void add(VSaleReturnlist vSaleReturnlist, String itemIds) {
		Salelist salelist = salelistDao.get(Salelist.class, vSaleReturnlist.getSlid());
		if (salelist != null) {
			SaleReturnlist saleReturnlist = new SaleReturnlist();
			BeanUtils.copyProperties(vSaleReturnlist, saleReturnlist);
			saleReturnlist.setSaleList(salelist);
			if (vSaleReturnlist.getUid() != null) {
				User user = new User();
				user.setId(vSaleReturnlist.getUid());
				saleReturnlist.setUser(user);
			}
			if (vSaleReturnlist.getRid() != null) {
				Repertory repertory = new Repertory();
				repertory.setId(vSaleReturnlist.getRid());
				saleReturnlist.setRepertory(repertory);
			}
			saleReturnlist.setMember(salelist.getMember());
			saleReturnlistDao.save(saleReturnlist);
			saleReturnlist = saleReturnlistDao.get(SaleReturnlist.class, saleReturnlist.getId());
			Double total = 0d;
			Double realReturn = 0d;
			String[] ids = itemIds.split(",");
			for (int i = 0; i < ids.length; i++) {
				SalelistItem item = salelistItemDao.get(SalelistItem.class, Long.parseLong(ids[i]));
				if (item != null) {
					total += item.getTotal();
					SaleReturnlistItem returnlistItem = new SaleReturnlistItem();
					returnlistItem.setGoods(item.getGoods());
					returnlistItem.setNum(item.getNumber());
					returnlistItem.setTotal(returnlistItem.getTotal());
					returnlistItem.setSaleReturnlist(saleReturnlist);
					saleReturnlistItemDao.save(returnlistItem);
					item.setRefund(true);
					salelistItemDao.update(item);
					Goods goods = item.getGoods();
					goods.setAmount(goods.getAmount()+item.getNumber());
					goods.setSaleReturnTotal(goods.getSaleReturnTotal()+item.getNumber());
					goodsDao.update(goods);
				}
			}
			realReturn = total;
			if (salelist.getPointNum() > 0) {
				PointUsedRecord pointUsedRecord = getPointUsedRecordBySalelist(salelist);
				if(pointUsedRecord!=null&&pointUsedRecord.getNum()>0){
					Member member = salelist.getMember();
					BasicArgument argument = getBasricArgumentByKey(saleReturnlist.getRepertory().getId(), Constants.INTEGRAL_CONVERSION_RATIO);
					Double amount = Double.valueOf(pointUsedRecord.getNum())/Integer.parseInt(argument.getArgValue());
					if(realReturn>=amount){//积分兑换金少于退款金额
						realReturn = realReturn-amount;
						pointUsedRecorDao.delete(pointUsedRecord);
						member.setPoint(member.getPoint()+pointUsedRecord.getNum());
						member.setConsume(member.getConsume()-realReturn);
						memberBaseDao.update(member);
					}else{//积分兑换金大于退款金额，退部分积分即可
						Integer num = Integer.parseInt(String.valueOf(realReturn*Integer.parseInt(argument.getArgValue())));
						pointUsedRecord.setNum(pointUsedRecord.getNum()-num);
						realReturn = realReturn-amount;
						pointUsedRecorDao.update(pointUsedRecord);
						member.setPoint(member.getPoint()+num-realReturn.intValue());
						memberBaseDao.update(member);
					}
				}
			}
			saleReturnlist.setTotal(total);
			saleReturnlist.setRealReturn(realReturn);
			saleReturnlistDao.update(saleReturnlist);
		}

	}
	
	private PointUsedRecord getPointUsedRecordBySalelist(Salelist salelist){
		String hql = "from PointUsedRecord t where t.salelist.id=?";
		List<Object> values = new ArrayList<Object>();
		values.add(salelist.getId());
		return pointUsedRecorDao.get(hql, values);
	}

	private BasicArgument getBasricArgumentByKey(Long rid, String key) {
		String hql = "from BasicArgument t where t.repertory.id=? and t.argKey=? ";
		List<Object> values = new ArrayList<Object>();
		values.add(rid);
		values.add(key);
		return basicArumentDao.get(hql, values);
	}

	private List<VSaleReturnlist> changeModel(List<SaleReturnlist> srls) {
		List<VSaleReturnlist> vsrls = new ArrayList<VSaleReturnlist>();
		if (srls != null && srls.size() > 0) {
			for (SaleReturnlist srl : srls) {
				VSaleReturnlist vsrl = new VSaleReturnlist();
				BeanUtils.copyProperties(srl, vsrl);
				if (srl.getUser() != null) {
					User user = srl.getUser();
					vsrl.setUid(user.getId());
					vsrl.setUusername(user.getUsername());
				}
				if (srl.getRepertory() != null) {
					Repertory repertory = srl.getRepertory();
					vsrl.setRid(repertory.getId());
					vsrl.setRname(repertory.getName());
				}
				if (srl.getSaleList() != null) {
					Salelist sl = srl.getSaleList();
					vsrl.setSlid(sl.getId());
				}
				if (srl.getMember() != null) {
					Member member = srl.getMember();
					vsrl.setMid(member.getId());
					vsrl.setMname(member.getName());
				}
				vsrls.add(vsrl);
			}
		}
		return vsrls;
	}

	private List<SaleReturnlist> find(VSaleReturnlist vsrl) {
		String hql = "from SaleReturnlist t where 1=1 ";

		List<Object> values = new ArrayList<Object>();
		hql = addWhere(vsrl, hql, values);

		if (vsrl.getSort() != null && vsrl.getOrder() != null) {
			hql += " order by " + vsrl.getSort() + " " + vsrl.getOrder();
		}
		return this.saleReturnlistDao.find(hql, values, vsrl.getPage(), vsrl.getRows());
	}

	private Long total(VSaleReturnlist vbrand) {
		String hql = "select count(*) from SaleReturnlist t where 1=1 ";
		List<Object> values = new ArrayList<Object>();
		hql = addWhere(vbrand, hql, values);
		return saleReturnlistDao.count(hql, values);
	}

	private String addWhere(VSaleReturnlist vsrl, String hql, List<Object> values) {
		if (vsrl.getId() != null) {
			hql += " and t.id = ? ";
			values.add(vsrl.getId());
		}

		if (vsrl.getSerial() != null) {
			hql += " and t.serial = ? ";
			values.add(vsrl.getSerial());
		}

		if (vsrl.getBeginDate() != null) {
			hql += " and t.date >= ? ";
			values.add(vsrl.getBeginDate());
		}

		if (vsrl.getEndDate() != null) {
			hql += " and t.date <= ? ";
			values.add(vsrl.getEndDate());
		}

		if (vsrl.getUid() != null) {
			hql += " and t.user.id = ? ";
			values.add(vsrl.getUid());
		}

		if (vsrl.getRid() != null) {
			hql += " and t.repertory.id = ? ";
			values.add(vsrl.getRid());
		}

		return hql;
	}

	@Override
	public List<VSaleReturnlist> combobox(VSaleReturnlist vsrl) {
		return this.changeModel(this.find(vsrl));
	}

	@Override
	public DataGrid datagrid(VSaleReturnlist vsrl) {
		DataGrid dg = new DataGrid();
		dg.setRows(this.changeModel(this.find(vsrl)));
		dg.setTotal(this.total(vsrl));
		return dg;
	}

	@Override
	public void delete(String ids) {
		if (ids != null) {
			for (String id : ids.split(",")) {
				if (!id.trim().equals("0")) {
					SaleReturnlist srl = this.saleReturnlistDao.get(SaleReturnlist.class, Long.parseLong(id.trim()));
					if (srl != null) {
						saleReturnlistDao.update(srl);
					}
				}
			}
		}
	}

	@Override
	public void update(VSaleReturnlist vsrl) {
		SaleReturnlist srl = saleReturnlistDao.get(SaleReturnlist.class, vsrl.getId());
		BeanUtils.copyProperties(vsrl, srl, new String[] { "id" });
		if (vsrl.getRid() != null) {
			srl.setRepertory(new Repertory(vsrl.getRid()));
		}
		if (vsrl.getUid() != null) {
			srl.setUser(new User(vsrl.getUid()));
		}
		if (vsrl.getMid() != null) {
			srl.setMember(new Member(vsrl.getMid()));
		}
		if (vsrl.getSlid() != null) {
			srl.setSaleList(new Salelist(vsrl.getSlid()));
		}
		this.saleReturnlistDao.update(srl);
	}

}
